#include "LocalMediaStream.h"
#include "ConnectionFactory.h"
#include "PublicFunHelper.h"
#include "CameraVideoCapture.h"
#include "CaptureVideoTrackSource.h"
#include "rtc_base/ref_counted_object.h"
#include <QLabel>
#include <QDebug>

LocalMediaStream* LocalMediaStream::m_pInstance = nullptr;

LocalMediaStream *LocalMediaStream::getInstance()
{
    if(m_pInstance == nullptr)
    {
        m_pInstance = new LocalMediaStream;
    }

    return m_pInstance;
}

LocalMediaStream::LocalMediaStream(QObject *parent)
    : QObject(parent)
{

}

void LocalMediaStream::init()
{
    rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factoryInter = ConnectionFactory::get();
    m_audioTrack = factoryInter->CreateAudioTrack(
                LABEL_AUDIO,
                factoryInter->CreateAudioSource(cricket::AudioOptions()));

    QStringList nameList, idList;
    PublicFunHelper::getCameraDevices(nameList, idList);
    if(idList.size() > 0)
    {
        openCamera(idList.at(0));
    }
}

void LocalMediaStream::openCamera(const QString &strID)
{
    rtc::scoped_refptr<CaptureVideoTrackSource> videoDev(
                CaptureVideoTrackSource::create(1920, 1080, 1, strID));
    setVideoTrackSource(videoDev);

}

void LocalMediaStream::setVideoTrackSource(rtc::scoped_refptr<webrtc::VideoTrackSource> source)
{
    if(source != nullptr)
    {
        source->state();
        rtc::scoped_refptr<webrtc::VideoTrackInterface> videoTrack =
                ConnectionFactory::get()->CreateVideoTrack(LABEL_VIDEO, source.get());
        m_videoTrack = videoTrack;
    }
}
